#include"c3pom/portalmanager.h"
#include"c3pom/application.h"
#include"c3pom/portalbufmanager.h"
#include"c3pom/pluginmanager.h"
#include<iostream>
#include<vector>
using namespace c3pom;
using namespace std;


static PortalManager* instance=NULL;

PortalManager::PortalManager()
{
	omp_init_lock(&lock);
	log=Log::getInstance();
	Application::getInstance()->regCommand(new Lspt());
}



Portal* PortalManager::regPortal(string name,string pbuf,string owner,string datatype)
{
	omp_set_lock(&lock);
	PortalMonitor* pm=portals[name];
	omp_unset_lock(&lock);
	if(pm==NULL)//未被建立过依赖或采用其他方式初始化过
	{
		pm=new PortalMonitor();
	}
	
	omp_set_lock(&pm->lock);
	Portal* portal=pm->portal;

	if(portal==NULL)//未建立portal
	{
		if(pm->owner==owner||pm->owner=="")
		{
			portal=new Portal();
	//根据pbuf生成一个portalbuf实例并设置给portal
			portal->portalBuf=PortalBufManager::getInstance()->createPortalBuf(pbuf);
		}
		else
		{
			omp_set_lock(&pm->lock);
			log->error("have no right to create portalbuf");
			return NULL;
		}
	}
	else//覆盖检测,默认不可被覆盖
	{
		if(pm->owner==owner)
		{
			omp_unset_lock(&pm->lock);
			log->error("portal has been registed");
			return portal;
		}
		else
		{
			omp_unset_lock(&pm->lock);
			log->error("portal has been used");
			return NULL;
		}
	}
	pm->portal=portal;
	pm->owner=owner;
	pm->statu="using";
	pm->datatype=datatype;
	omp_unset_lock(&pm->lock);

	omp_set_lock(&lock);
	portals[name]=pm;
	omp_unset_lock(&lock);
	
	return portal;
}
Portal* PortalManager::findPortal(string portalname)
{
	Portal* portal=NULL;
	omp_set_lock(&lock);
	PortalMonitor* pm=portals[portalname];
	if(pm!=NULL)
	{
		omp_set_lock(&pm->lock);
		portal=pm->portal;
	}
	omp_unset_lock(&lock);
	return portal;
}
string PortalManager::name()
{
	return "portalmanager";
}

string PortalManager::desc()
{
	return "portal管理器";
}
void PortalManager::run()
{
}
PortalManager* PortalManager::getInstance()
{
	if(instance==NULL)
		instance=new PortalManager();
	return instance;
}


string PortalManager::Lspt::name()
{
	return "lspt";
}

string PortalManager::Lspt::desc()
{
	return "portal列表";
}

int PortalManager::Lspt::exec(vector<string>)
{
	PortalManager* pm=PortalManager::getInstance();
	if(pm!=NULL)
	{
		omp_set_lock(&pm->lock);
		cout<<"portal list:"<<endl;
		cout<<"name\towner\tdatatype\tstatu\tlength"<<endl;
		map<string,PortalMonitor*>::const_iterator map_it=pm->portals.begin();
		for(;map_it!=pm->portals.end();map_it++)
		{
			int length=-1;
			PortalMonitor* portalMonitor=map_it->second;
			
			if((portalMonitor!=NULL)&&(portalMonitor->portal!=NULL))
			{
				length=portalMonitor->portal->dataLength();
			}
			
			cout<<map_it->first<<"\t"<<map_it->second->owner<<"\t"<<map_it->second->datatype<<"\t"<<map_it->second->statu<<"\t"<<length<<endl;
		}
		omp_unset_lock(&pm->lock);
	}
	return 0;
}


PortalMonitor::PortalMonitor()
{
	omp_init_lock(&lock);
	portal=NULL;
	statu="unknown";
}

